import re

# Some regexes
RE_spaces = re.compile('\ +')
RE_braces = re.compile(r'\(.*\)')
RE_braces2 = re.compile(r'\[.*\]')
RE_year = re.compile('(19|20)\d\d')
RE_info = re.compile('(Divx|dvdrip|vhs|xvid|vcd|telecine|kinowka|lektor|DVDSCR|screener)', re.I)
RE_trash = re.compile('\W+')
RE_bad = re.compile(r'(%s)' % r'|'.join(sorted([r"\b%s\b"%x.strip() for x in """
_uploaded__t ac3 adinfimum afo avi axxo best
bodeha bone by ch d deity deity dmd_s3k dokoncz
f flint gumi554 immortals info internal iverson
iverson3 jk lek lmg moviex napisy o pawel
pawel80 please prosz prosze pukka qix release
rex rmvb s3k swepnet t tc tess tnp tus uploaded
uploaded w www

STV SAPHiRE k Jamgood LiMiTED ENCODRS
dokonczprosze dvd iso iNT MoMo fico
DO WYCIAGNIECIA SRODKU REPACK XanaX
Jarodpol   2CD comete 1cd janneau
mozna prosic dokonczenie dolaczam sie prosby
maniek ma ktos lepsza jakosc wersje
kin wka
""".split()])), re.I)
RE_lang = re.compile('\b(eng|pl)\b', re.I)

def get_title(filename):
    """ Zwraca prawdopodobny tytul filmu z nazwy katalogu 
    
    TODO: Doctests
    """
    # Trash to spaces
    title = filename.replace('_', ' ')
    title = RE_spaces.sub(' ', RE_trash.sub(' ', title))

    # Kill words known as bas
    title = RE_bad.sub('', title)

    # And other things
    title = RE_lang.sub('', title)
    title = RE_braces.sub('', title)
    title = RE_braces2.sub('', title)
    title = RE_year.sub('', title)
    title = RE_info.sub('', title)
    title = RE_spaces.sub(' ', RE_trash.sub(' ', title))

    return title.strip()

def get_year(filename):
    """ Gets year out of filename 
    
    TODO: Doctests
    """
    try:
        year = int(RE_year.search(filename).group())
    except Exception, e:
        year = None
    return year

if __name__ == "__main__":
    print get_title("Dupa JAsio")
    print get_year("Dupa 9123 1924")
